#include "operatordialog.h"
#include "ui_operatordialog.h"

#include <QSqlTableModel>

OperatorDialog::OperatorDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OperatorDialog)
{
    ui->setupUi(this);
    this->loadData();
}

OperatorDialog::~OperatorDialog()
{
    delete ui;
}

void OperatorDialog::accept()
{
    if(ui->name_lineEdit->text().isEmpty() || ui->note_lineEdit->text().isEmpty() || ui->department_comboBox->currentText().isEmpty())
        return;
    QDialog::accept();
}

void OperatorDialog::setOperator(const int operator_id)
{
    setWindowTitle(tr("Operator (edit)"));
    QSqlTableModel *model = new QSqlTableModel(this);
    model->setTable("operators");
    model->select();

    QModelIndexList item = model->match(model->index( 0, model->fieldIndex("id")), Qt::DisplayRole, operator_id,  1, Qt::MatchExactly);
    //ui->measure_comboBox->setCurrentIndex(ui->measure_comboBox->findData(model->data(model->index(item[0].row(), model->fieldIndex("measure"))).toString(), Qt::EditRole));
    ui->name_lineEdit->setText(model->data(model->index(item[0].row(), model->fieldIndex("name"))).toString());
    ui->note_lineEdit->setText(model->data(model->index(item[0].row(), model->fieldIndex("note"))).toString());
    int department_id = model->data(model->index(item[0].row(), model->fieldIndex("department_id"))).toInt();
    this->setDepartment(department_id);
}

QString OperatorDialog::getName() const
{
    return ui->name_lineEdit->text();
}

QString OperatorDialog::getNote() const
{
    return ui->note_lineEdit->text();
}

QString OperatorDialog::getDepartment() const
{
    return ui->department_comboBox->currentText();
}

int OperatorDialog::getDepartmentId() const
{
    QSqlTableModel *model = qobject_cast<QSqlTableModel *>(ui->department_comboBox->model());
    if(model){
        QString field("id");
        return model->data(model->index(ui->department_comboBox->currentIndex(), model->fieldIndex(field))).toInt();
    }
    return -1;
}

void OperatorDialog::loadData()
{
    QSqlTableModel *model = new QSqlTableModel(ui->department_comboBox);
    model->setTable("departments");
    model->select();

    ui->department_comboBox->setModel(model);
    ui->department_comboBox->setModelColumn(model->fieldIndex("department"));
    ui->department_comboBox->setCurrentIndex(0);
}

void OperatorDialog::setDepartment(const int department_id)
{
    QSqlTableModel *model = qobject_cast<QSqlTableModel *>(ui->department_comboBox->model());
    if(model){
        QModelIndexList Departments = model->match(model->index( 0, model->fieldIndex("id")), Qt::DisplayRole, department_id,  1, Qt::MatchExactly);
        ui->department_comboBox->setCurrentIndex(Departments[0].row());
    }
}
